#ifndef __BLOCK_QUEUE_HPP__
#define __BLOCK_QUEUE_HPP__

#include <iostream>
#include <pthread.h>
#include <queue>

template <typename T>
class BlockQueue
{
private:
    bool IsFull()
    {
        return _block_queue.size() == _cap;
    }
    bool IsEmpty()
    {
        return _block_queue.empty();
    }

public:
    BlockQueue(int cap) : _cap(cap)
    {
        pthread_mutex_init(&_mutex, nullptr);
        pthread_cond_init(&_product_cond, nullptr);
        pthread_cond_init(&_consumer_cond, nullptr);
    }
    void Enqueu(T &in) // 生产者用的接口
    {
        pthread_mutex_lock(&_mutex);
        // while保证被唤醒后也会进行判断, 防止伪唤醒
        while (IsFull())
        {
            pthread_cond_wait(&_product_cond, &_mutex);
        }
        std::cout << in << std::endl;
        _block_queue.push(in);

        pthread_cond_signal(&_consumer_cond);
        pthread_mutex_unlock(&_mutex);
    }
    void Pop(T *out) // 消费者用的接口
    {
        pthread_mutex_lock(&_mutex);
        while (IsEmpty())
        {
            pthread_cond_wait(&_consumer_cond, &_mutex);
        }
        *out = _block_queue.front();
        _block_queue.pop();

        pthread_cond_signal(&_product_cond);
        pthread_mutex_unlock(&_mutex);
    }

    ~BlockQueue()
    {
        pthread_mutex_destroy(&_mutex);
        pthread_cond_destroy(&_product_cond);
        pthread_cond_destroy(&_consumer_cond);
    }

private:
    std::queue<T> _block_queue;
    int _cap;
    pthread_mutex_t _mutex;
    pthread_cond_t _product_cond;
    pthread_cond_t _consumer_cond;
};

#endif